<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 * @version    $Id: VideoController.php 2011-03-09 08:45:41Z idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 */

class Vote_VideoController extends Core_Controller_Action_Standard {
	public function init() {
		if (! $this->_helper->requireAuth ()->setAuthParams ( 'vote_challenge', null, 'view' )->isValid ())
			return;
		
		$id = $this->_getParam ( 'id', $this->_getParam ( 'challenge_id', 0 ) );
		if ($id) {
			if (! Engine_Api::_ ()->core ()->hasSubject ()) {
				$subject = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' )->find ( $id )->current ();
				if ($subject && $subject->getIdentity ()) {
					Engine_Api::_ ()->core ()->setSubject ( $subject );
				}
			}
		}
	}
	
	public function browseAction() {
		$this->_forward ( 'index' );
	}
	
	public function indexAction() {
		$this->view->navigation = $navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'vote_main_video', array (), 'vote_main_video_index' );
		
		$settings = Engine_Api::_ ()->getApi ( 'settings', 'core' );
		
		$this->view->params = $params = array ('type' => 'video', 'keyword' => $this->_getParam ( 'keyword', '' ), 'tag' => $this->_getParam ( 'tag', '' ), 'page' => $this->_getParam ( 'page', 1 ), 'ipp' => $settings->getSetting ( 'vote.page.count', 8 ), 'category' => $this->_getParam ( 'category', $this->_getParam ( 'category_id', 0 ) ), 'sort' => $this->_getParam ( 'sort', $this->_getParam ( 'orderby', '' ) ), 'has_photo' => $this->_getParam ( 'has_photo', 0 ), 'period' => $this->_getParam ( 'period', '' ), 'show' => $this->_getParam ( 'show', '' ), 'approved' => 1 );
		
		$table = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' );
		$this->view->paginator = $paginator = $table->getPaginator ( $params );
		$this->view->viewer = $viewer = Engine_Api::_ ()->user ()->getViewer ();
		$this->view->can_create = Engine_Api::_ ()->vote ()->isAllowedCreation ();
		
		$this->view->form = $form = new Vote_Form_Photo_Search ();
		$form->setAction ( $this->view->url ( array ('controller' => 'video', 'action' => 'index' ), 'vote_general', true ) );
		$form->populate ( $params );
		
		$values = array ('type' => 'video', 'approved' => 1 );
		$this->view->tags = Engine_Api::_ ()->vote ()->getTags ( $values );
		
		$ids = array ();
		foreach ( $paginator as $voting ) {
			$ids [] = $voting->getIdentity ();
		}
		
		if (empty ( $ids )) {
			return;
		}
		
		$cnt = count ( $ids );
		$limit = ( int ) ($cnt * 16);
		
		$table = Engine_Api::_ ()->getDbTable ( 'participants', 'vote' );
		$select = $table->select ()->where ( 'challenge_id IN (?)', $ids )->where ( 'status = 1' )->limit ( $limit );
		
		$data = $table->fetchAll ( $select );
		$participants = array ();
		
		foreach ( $data as $row ) {
			$challenge_id = $row->challenge_id;
			if (empty ( $participants [$challenge_id] )) {
				$participants [$challenge_id] = array ();
			}
			$participants [$challenge_id] [] = $row;
		}
		
		$this->view->participants = $participants;
	}
	
	public function manageAction() {
		if (! $this->_helper->requireAuth ()->setAuthParams ( 'vote_challenge', null, 'edit' )->isValid ())
			return;
		if (! $this->_helper->requireUser ()->isValid ())
			return;
		
		$this->view->navigation = $navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'vote_main_video', array (), 'vote_main_video_manage' );
		
		$settings = Engine_Api::_ ()->getApi ( 'settings', 'core' );
		
		$this->view->params = $params = array ('type' => 'video', 'keyword' => $this->_getParam ( 'keyword', '' ), 'tag' => $this->_getParam ( 'tag', '' ), 'page' => $this->_getParam ( 'page', 1 ), 'ipp' => $settings->getSetting ( 'vote.page.count', 8 ), 'category' => $this->_getParam ( 'category', $this->_getParam ( 'category_id', 0 ) ), 'sort' => $this->_getParam ( 'sort', $this->_getParam ( 'orderby', '' ) ), 'has_photo' => $this->_getParam ( 'has_photo', 0 ), 'period' => $this->_getParam ( 'period', '' ), 'user_id' => Engine_Api::_ ()->user ()->getViewer ()->getIdentity () );
		
		$table = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' );
		$this->view->paginator = $paginator = $table->getPaginator ( $params );
		$this->view->viewer = $viewer = Engine_Api::_ ()->user ()->getViewer ();
		$this->view->can_create = Engine_Api::_ ()->vote ()->isAllowedCreation ();
		
		$this->view->form = $form = new Vote_Form_Photo_Search ();
		$form->setAction ( $this->view->url ( array ('controller' => 'video', 'action' => 'manage' ), 'vote_general', true ) );
		$form->removeElement ( 'show' );
		$form->populate ( $params );
	}
	
	public function createAction() {
		if (! $this->_helper->requireAuth ()->setAuthParams ( 'vote_challenge', null, 'create' )->isValid ())
			return;
		if (! $this->_helper->requireUser ()->isValid ())
			return;
		
		$this->view->navigation = $navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'vote_main_video', array (), 'vote_main_video_create' );
		
		$this->view->viewer = $viewer = Engine_Api::_ ()->user ()->getViewer ();
		$this->view->form = $form = new Vote_Form_Create ();
		$options = Engine_Api::_ ()->vote ()->getCategoryOptions ( 'video' );
		if (! empty ( $options )) {
			$form->category_id->setMultiOptions ( $options );
		} else {
			$form->removeElement ( 'category_id' );
		}
		
		if (! $this->getRequest ()->isPost ()) {
			return;
		}
		
		$values = $this->getRequest ()->getPost ();
		if (! $form->isValid ( $values )) {
			$form->populate ( $values );
			return;
		}
		
		$values = $form->getValues ();
		$values ['slug'] = Engine_Api::_ ()->kowcore ()->strToSlug ( $values ['title'] );
		$values ['creation_date'] = date ( 'Y-m-d H:i:s' );
		$values ['modified_date'] = date ( 'Y-m-d H:i:s' );
		$values ['user_id'] = $viewer->getIdentity ();
		$values ['approved'] = ( int ) (! Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'vote_approval', 0 ));
		$values ['type'] = 'video';
		
		if (Engine_Api::_ ()->vote ()->checkSlug ( null, $values ['slug'] )) {
			$form->addError ( 'Please provide another title. Voting with this title already exists.' );
			return;
		}
		
		$oldTz = date_default_timezone_get ();
		date_default_timezone_set ( $viewer->timezone );
		
		$start = strtotime ( $values ['starttime'] );
		$end = strtotime ( $values ['endtime'] );
		$now = time ();
		
		if ($start < $now) {
			$form->addError ( 'vote_Start time must be in the future.' );
			return;
		}
		
		if ($end < $now) {
			$form->addError ( 'vote_End time must be in the future.' );
			return;
		}
		
		if ($values ['endtime'] < $values ['starttime']) {
			$form->addError ( 'End time must be in the future.' );
			return;
		}
		
		date_default_timezone_set ( $oldTz );
		
		$values ['starttime'] = date ( 'Y-m-d H:i:s', $start );
		$values ['endtime'] = date ( 'Y-m-d H:i:s', $end );
		
		$table = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' );
		$db = $table->getAdapter ();
		$db->beginTransaction ();
		
		try {
			$voting = $table->createRow ();
			$voting->setFromArray ( $values );
			$voting->save ();
			
			$raw_tags = preg_split ( '/[,]+/', $values ['tags'] );
			$tags = array ();
			foreach ( $raw_tags as $tag ) {
				$tag = trim ( strip_tags ( $tag ) );
				if ($tag == "") {
					continue;
				}
				$tags [] = $tag;
			}
			
			$voting->tags ()->addTagMaps ( $viewer, $tags );
			$voting->keywords = implode ( ', ', $tags );
			$voting->save ();
			
			if (! empty ( $values ['photo'] )) {
				$voting->setPhoto ( $form->photo );
			}
			
			$auth = Engine_Api::_ ()->authorization ()->context;
			$roles = array ('owner', 'member', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
			
			$viewMax = array_search ( $values ['auth_view'], $roles );
			$commentMax = array_search ( $values ['auth_comment'], $roles );
			$partMax = array_search ( $values ['auth_participate'], $roles );
			$voteMax = array_search ( $values ['auth_vote'], $roles );
			
			foreach ( $roles as $i => $role ) {
				$auth->setAllowed ( $voting, $role, 'view', ($i <= $viewMax) );
				$auth->setAllowed ( $voting, $role, 'comment', ($i <= $commentMax) );
				$auth->setAllowed ( $voting, $role, 'participate', ($i <= $partMax) );
				$auth->setAllowed ( $voting, $role, 'vote', ($i <= $voteMax) );
			}
			
			$activityApi = Engine_Api::_ ()->getDbTable ( 'actions', 'activity' );
			$action = $activityApi->addActivity ( $viewer, $voting, 'vote_challenge_new' );
			
			$db->commit ();
			
			return $this->_helper->redirector->gotoRoute ( array ('id' => $voting->getSlug () ), 'vote_profile', true );
		} catch ( Engine_Image_Exception $e ) {
			$db->rollBack ();
			$form->addError ( Zend_Registry::get ( 'Zend_Translate' )->_ ( 'The image you selected was too large.' ) );
		} catch ( Exception $e ) {
			$db->rollBack ();
			throw $e;
		}
	
	}
	
	public function editAction() {
		if (! $this->_helper->requireUser ()->isValid ())
			return;
		if (! $this->_helper->requireAuth ()->setAuthParams ( 'vote_challenge', null, 'edit' )->isValid ())
			return;
		
		$this->view->navigation = $navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'vote_main_video', array (), 'vote_main_video_manage' );
		
		$this->view->viewer = $viewer = Engine_Api::_ ()->user ()->getViewer ();
		$this->view->form = $form = new Vote_Form_Edit ();
		$options = Engine_Api::_ ()->vote ()->getCategoryOptions ( 'video' );
		if (! empty ( $options )) {
			$form->category_id->setMultiOptions ( $options );
		} else {
			$form->removeElement ( 'category_id' );
		}
		
		$challenge_id = $this->_getParam ( 'challenge_id', 0 );
		if (! $challenge_id) {
			$this->_helper->redirector->gotoRoute ( array ('action' => 'index' ), 'vote_general', true );
			return;
		}
		
		$voting = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' )->find ( $challenge_id )->current ();
		if (! $voting->getIdentity ()) {
			$this->_helper->redirector->gotoRoute ( array ('action' => 'index' ), 'vote_general', true );
			return;
		}
		
		if ($voting->isStarted ()) {
			$this->_helper->redirector->gotoRoute ( array ('action' => 'index' ), 'vote_general', true );
			return false;
		}
		
		$roles = array ('owner', 'member', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
		if (! $this->getRequest ()->isPost ()) {
			$form->populate ( $voting->toArray () );
			$form->tags->setValue ( $voting->keywords );
			
			$auth = Engine_Api::_ ()->authorization ()->context;
			foreach ( $roles as $role ) {
				if (1 === $auth->isAllowed ( $voting, $role, 'view' )) {
					$form->auth_view->setValue ( $role );
				}
				if (1 === $auth->isAllowed ( $voting, $role, 'comment' )) {
					$form->auth_comment->setValue ( $role );
				}
				if (1 === $auth->isAllowed ( $voting, $role, 'participate' )) {
					$form->auth_participate->setValue ( $role );
				}
				if (1 === $auth->isAllowed ( $voting, $role, 'vote' )) {
					$form->auth_vote->setValue ( $role );
				}
			}
			
			return;
		}
		
		$values = $this->getRequest ()->getPost ();
		if (! $form->isValid ( $values )) {
			$form->populate ( $values );
			return;
		}
		
		$values = $form->getValues ();
		$values ['slug'] = Engine_Api::_ ()->kowcore ()->strToSlug ( $values ['title'] );
		if (Engine_Api::_ ()->vote ()->checkSlug ( $voting, $values ['slug'] )) {
			$form->addError ( 'Please provide another title for voting.' );
			return;
		}
		
		$values ['creation_date'] = date ( 'Y-m-d H:i:s' );
		$values ['modified_date'] = date ( 'Y-m-d H:i:s' );
		
		$oldTz = date_default_timezone_get ();
		date_default_timezone_set ( $viewer->timezone );
		
		$start = strtotime ( $values ['starttime'] );
		$end = strtotime ( $values ['endtime'] );
		$now = time ();
		
		if ($start < $now) {
			$form->addError ( 'vote_Start time must be in the future.' );
			return;
		}
		
		if ($end < $now) {
			$form->addError ( 'vote_End time must be in the future.' );
			return;
		}
		
		if ($values ['endtime'] < $values ['starttime']) {
			$form->addError ( 'vote_End time must be in the future.' );
			return;
		}
		
		date_default_timezone_set ( $oldTz );
		
		$values ['starttime'] = date ( 'Y-m-d H:i:s', $start );
		$values ['endtime'] = date ( 'Y-m-d H:i:s', $end );
		
		$table = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' );
		$db = $table->getAdapter ();
		$db->beginTransaction ();
		
		try {
			$voting->setFromArray ( $values );
			$voting->save ();
			
			$raw_tags = preg_split ( '/[,]+/', $values ['tags'] );
			$tags = array ();
			foreach ( $raw_tags as $tag ) {
				$tag = trim ( strip_tags ( $tag ) );
				if ($tag == "") {
					continue;
				}
				$tags [] = $tag;
			}
			
			$voting->tags ()->addTagMaps ( $viewer, $tags );
			$voting->keywords = implode ( ', ', $tags );
			$voting->save ();
			
			if (! empty ( $values ['photo'] )) {
				$voting->setPhoto ( $form->photo );
			}
			
			$viewMax = array_search ( $values ['auth_view'], $roles );
			$commentMax = array_search ( $values ['auth_comment'], $roles );
			$partMax = array_search ( $values ['auth_participate'], $roles );
			$voteMax = array_search ( $values ['auth_vote'], $roles );
			
			// CREATE AUTH STUFF HERE
			$auth = Engine_Api::_ ()->authorization ()->context;
			$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
			if ($values ['auth_view']) {
				$auth_view = $values ['auth_view'];
			} else {
				$auth_view = "everyone";
			}
			$viewMax = array_search ( $auth_view, $roles );
			foreach ( $roles as $i => $role ) {
				$auth->setAllowed ( $voting, $role, 'view', ($i <= $viewMax) );
			}
			
			$auth = Engine_Api::_ ()->authorization ()->context;
			$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
			if ($values ['auth_comment']) {
				$auth_comment = $values ['auth_comment'];
			} else {
				$auth_comment = "everyone";
			}
			$commentMax = array_search ( $auth_comment, $roles );
			foreach ( $roles as $i => $role ) {
				$auth->setAllowed ( $voting, $role, 'comment', ($i <= $commentMax) );
			}
			
			$auth = Engine_Api::_ ()->authorization ()->context;
			$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
			if ($values ['auth_participate']) {
				$auth_participate = $values ['auth_participate'];
			} else {
				$auth_participate = "everyone";
			}
			$participateMax = array_search ( $auth_participate, $roles );
			foreach ( $roles as $i => $role ) {
				$auth->setAllowed ( $voting, $role, 'participate', ($i <= $participateMax) );
			}
			
			$auth = Engine_Api::_ ()->authorization ()->context;
			$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
			if ($values ['auth_vote']) {
				$auth_vote = $values ['auth_vote'];
			} else {
				$auth_vote = "everyone";
			}
			$voteMax = array_search ( $auth_vote, $roles );
			foreach ( $roles as $i => $role ) {
				$auth->setAllowed ( $voting, $role, 'vote', ($i <= $voteMax) );
			}
			
			$db->commit ();
			
			return $this->_helper->redirector->gotoRoute ( array ('id' => $voting->getSlug () ), 'vote_profile', true );
		} catch ( Engine_Image_Exception $e ) {
			$db->rollBack ();
			$form->addError ( Zend_Registry::get ( 'Zend_Translate' )->_ ( 'The image you selected was too large.' ) );
		} catch ( Exception $e ) {
			$db->rollBack ();
			throw $e;
		}
	
	}
	
	public function viewAction() {
		$id = $this->_getParam ( 'pid' );
		if (! $id) {
			return $this->_helper->redirector->gotoRoute ( array (), 'vote_general', true );
		}
		
		$table = Engine_Api::_ ()->getDbTable ( 'participants', 'vote' );
		$this->view->participant = $participant = $table->find ( $id )->current ();
		if (! $participant) {
			return $this->_helper->redirector->gotoRoute ( array (), 'vote_general', true );
		}
		$this->view->voting = $voting = $participant->getVoting ();
		$this->view->viewer = $viewer = $this->_helper->api ()->user ()->getViewer ();
		$this->view->canVote = $voting->isStarted () && $voting->authorization ()->isAllowed ( null, 'vote' );
		
		$this->_helper->requireAuth ()->setNoForward ()->setAuthParams ( $participant, Engine_Api::_ ()->user ()->getViewer (), 'view' );
		
		if ($participant->getIdentity ()) {
			$participant->view_count ++;
			$participant->save ();
		}
		
		$embedded = "";
		if ($participant->status == 1) {
			$embedded = $participant->getRichContent ( true );
		}
		
		if ($participant->ptype == 3 && $participant->status != 0) {
			if (! empty ( $participant->file_id )) {
				$storage_file = Engine_Api::_ ()->getItem ( 'storage_file', $participant->file_id );
				if ($storage_file) {
					$this->view->video_location = $storage_file->map ();
				}
			}
		}
		
		$this->view->viewer_id = $viewer->getIdentity ();
		$this->view->videoEmbedded = $embedded;
		
		$tpl = $voting->type . '/view-normal.tpl';
		$format = $this->_getParam ( 'format' );
		
		if ($format == 'smoothbox') {
			$tpl = $voting->type . '/view-smoothbox.tpl';
		}
		
		$this->view->html = $this->view->render ( $tpl );
	}
	
	public function uploadAction() {
		if (! $this->_helper->requireUser->isValid ())
			return;
		if (! $this->_helper->requireAuth ()->setAuthParams ( 'vote_challenge', null, 'participate' )->isValid ())
			return;
		
		// Upload video
		if (isset ( $_GET ['ul'] ) || isset ( $_FILES ['Filedata'] )) {
			return $this->_forward ( 'upload-video', null, null, array ('format' => 'json' ) );
		}
		
		if (! $this->getRequest ()->isPost ()) {
			return $this->_helper->redirector->gotoRoute ( array (), 'vote_general', true );
		}
		
		$challenge_id = ( int ) $this->_getParam ( 'challenge_id', 0 );
		if (! $challenge_id) {
			return $this->_helper->redirector->gotoRoute ( array (), 'vote_general', true );
		}
		
		$table = Engine_Api::_ ()->getDbtable ( 'challenges', 'vote' );
		$voting = $table->find ( $challenge_id )->current ();
		if (! $voting->getIdentity ()) {
			return $this->_helper->redirector->gotoRoute ( array (), 'vote_general', true );
		}
		
		$ptype = $this->_getParam ( 'ptype' );
		$id = $this->_getParam ( 'id', 0 );
		if (! $id && $ptype == 3) {
			return $this->_helper->redirector->gotoRoute ( array ('id' => $voting->getSlug () ), 'vote_profile', true );
		}
		
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		if ($voting->isParticipated ( $viewer, $id )) {
			return $this->_helper->redirector->gotoRoute ( array ('id' => $voting->getSlug () ), 'vote_profile', true );
		}
		
		if (! $voting->authorization ()->isAllowed ( null, 'participate' )) {
			return $this->_helper->redirector->gotoRoute ( array ('id' => $voting->getSlug () ), 'vote_profile', true );
		}
		
		if ($voting->isFinished ()) {
			return $this->_helper->redirector->gotoRoute ( array ('id' => $voting->getSlug () ), 'vote_profile', true );
		}
		
		$values = $this->_getAllParams ();
		$viewer = $this->_helper->api ()->user ()->getViewer ();
		$values ['user_id'] = $viewer->getIdentity ();
		$values ['ptype'] = $values ['video_type'];
		$values ['type'] = 'video';
		$values ['challenge_id'] = $voting->getIdentity ();
		$values ['search'] = ( int ) $voting->search;
		
		$table = Engine_Api::_ ()->getDbTable ( 'participants', 'vote' );
		$db = $table->getAdapter ();
		$db->beginTransaction ();
		
		$insert_action = false;
		
		try {
			if ($ptype == 3) {
				$part = Engine_Api::_ ()->getItem ( 'vote_participant', $id );
			} else {
				$part = $table->createRow ();
			}
			
			$part->setFromArray ( $values );
			$part->save ();
			
			// Now try to create thumbnail
			$thumbnail = $this->handleThumbnail ( $part->ptype, $part->code );
			$ext = ltrim ( strrchr ( $thumbnail, '.' ), '.' );
			$thumbnail_parsed = @parse_url ( $thumbnail );
			
			if (@GetImageSize ( $thumbnail )) {
				$valid_thumb = true;
			} else {
				$valid_thumb = false;
			}
			
			if ($valid_thumb && $thumbnail && $ext && $thumbnail_parsed && in_array ( $ext, array ('jpg', 'jpeg', 'gif', 'png' ) )) {
				$tmp_file = APPLICATION_PATH . '/temporary/link_' . md5 ( $thumbnail ) . '.' . $ext;
				$thumb_file = APPLICATION_PATH . '/temporary/link_thumb_' . md5 ( $thumbnail ) . '.' . $ext;
				
				$src_fh = fopen ( $thumbnail, 'r' );
				$tmp_fh = fopen ( $tmp_file, 'w' );
				stream_copy_to_stream ( $src_fh, $tmp_fh, 1024 * 1024 * 2 );
				
				$image = Engine_Image::factory ();
				$image->open ( $tmp_file )->resize ( 120, 240 )->write ( $thumb_file )->destroy ();
				
				try {
					$thumbFileRow = Engine_Api::_ ()->storage ()->create ( $thumb_file, array ('parent_type' => $part->getType (), 'parent_id' => $part->getIdentity () ) );
					
					// Remove temp file
					@unlink ( $thumb_file );
					@unlink ( $tmp_file );
				
				} catch ( Exception $e ) {
				
				}
				$information = $this->handleInformation ( $part->ptype, $part->code );
				
				$part->duration = $information ['duration'];
				
				if (! $part->description) {
					$part->description = $information ['description'];
				}
				
				$part->photo_id = $thumbFileRow->file_id;
				$part->status = 1;
				$part->save ();
				
				// Insert new action item
				$insert_action = true;
			}
			
			if ($values ['ignore'] == true) {
				$part->status = 1;
				$part->save ();
				$insert_action = true;
			}
			
			$voting->participant_count ++;
			$voting->save ();
			
			$db->commit ();
		} 

		catch ( Exception $e ) {
			$db->rollBack ();
			throw $e;
		}
		
		$db->beginTransaction ();
		try {
			if ($insert_action) {
				$activityApi = Engine_Api::_ ()->getDbTable ( 'actions', 'activity' );
				$action = $activityApi->addActivity ( $viewer, $voting, 'vote_participated' );
			}
			
			$db->commit ();
		} catch ( Exception $e ) {
			$db->rollBack ();
			throw $e;
		}
		
		return $this->_helper->redirector->gotoRoute ( array ('id' => $voting->getSlug () ), 'vote_profile', true );
	}
	
	public function uploadVideoAction() {
		if (! $this->_helper->requireUser ()->checkRequire ()) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Max file size limit exceeded (probably).' );
			return;
		}
		
		if (! $this->getRequest ()->isPost ()) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Invalid request method' );
			return;
		}
		
		$values = $this->getRequest ()->getPost ();
		
		if (empty ( $values ['Filename'] )) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'No file' );
			return;
		}
		
		if (! isset ( $_FILES ['Filedata'] ) || ! is_uploaded_file ( $_FILES ['Filedata'] ['tmp_name'] )) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Invalid Upload' ) . print_r ( $_FILES, true );
			return;
		}
		
		$illegal_extensions = array ('php', 'pl', 'cgi', 'html', 'htm', 'txt' );
		if (in_array ( pathinfo ( $_FILES ['Filedata'] ['name'], PATHINFO_EXTENSION ), $illegal_extensions )) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Invalid Upload' );
			return;
		}
		
		$challenge_id = $this->_getParam ( 'challenge_id' );
		if (! $challenge_id) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Invalid Upload' );
			return;
		}
		
		$voting = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' )->find ( $challenge_id )->current ();
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		if ($voting->isParticipated ( $viewer )) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'You already participating in the voting.' );
			return;
		}
		
		if (! $voting->getIdentity () || ! $voting->authorization ()->isAllowed ( null, 'participate' )) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Invalid Upload' );
			return;
		}
		
		if ($voting->isFinished ()) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Voting already finished.' );
			return;
		}
		
		$db = Engine_Api::_ ()->getDbtable ( 'participants', 'vote' )->getAdapter ();
		$db->beginTransaction ();
		
		try {
			$viewer = Engine_Api::_ ()->user ()->getViewer ();
			$params = array ('owner_type' => 'user', 'owner_id' => $viewer->getIdentity () );
			$participant = Engine_Api::_ ()->vote ()->createVideoParticipant ( $params, $_FILES ['Filedata'] );
			
			$this->view->status = true;
			$this->view->name = $_FILES ['Filedata'] ['name'];
			$this->view->code = $participant->code;
			$this->view->participant_id = $participant->getIdentity ();
			
			// sets up title and owner_id now just incase members switch page as soon as upload is completed
			$participant->title = $_FILES ['Filedata'] ['name'];
			$participant->user_id = $viewer->getIdentity ();
			$participant->save ();
			
			$db->commit ();
		} catch ( Exception $e ) {
			$db->rollBack ();
			$this->view->status = false;
			$this->view->error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'An error occurred.' ) . $e;
			// throw $e;
			return;
		}
	}
	
	public function validationAction() {
		$video_type = $this->_getParam ( 'type' );
		$code = $this->_getParam ( 'code' );
		$ajax = $this->_getParam ( 'ajax', false );
		$valid = false;
		
		// check which API should be used
		if ($video_type == "youtube") {
			$valid = $this->checkYouTube ( $code );
		}
		
		if ($video_type == "vimeo") {
			$valid = $this->checkVimeo ( $code );
		}
		
		$this->view->code = $code;
		$this->view->ajax = $ajax;
		$this->view->valid = $valid;
	}
	
	public function extractCode($url, $type) {
		switch ($type) {
			//youtube
			case "1" :
				// change new youtube URL to old one
				$url = preg_replace ( "/#!/", "?", $url );
				
				// get v variable from the url
				$arr = array ();
				$arr = @parse_url ( $url );
				$code = "code";
				$parameters = $arr ["query"];
				parse_str ( $parameters, $data );
				$code = $data ['v'];
				
				return $code;
			//vimeo
			case "2" :
				// get the first variable after slash
				$code = @pathinfo ( $url );
				return $code ['basename'];
		}
	}
	
	// YouTube Functions
	public function checkYouTube($code) {
		if (! $data = @file_get_contents ( "http://gdata.youtube.com/feeds/api/videos/" . $code ))
			return false;
		if ($data == "Video not found")
			return false;
		return true;
	}
	
	// Vimeo Functions
	public function checkVimeo($code) {
		//http://www.vimeo.com/api/docs/simple-api
		//http://vimeo.com/api/v2/video
		$data = @simplexml_load_file ( "http://vimeo.com/api/v2/video/" . $code . ".xml" );
		$id = count ( $data->video->id );
		if ($id == 0)
			return false;
		return true;
	}
	
	// handles thumbnails
	public function handleThumbnail($type, $code = null) {
		switch ($type) {
			//youtube
			case "1" :
				//http://img.youtube.com/vi/Y75eFjjgAEc/default.jpg
				return "http://img.youtube.com/vi/$code/default.jpg";
			//vimeo
			case "2" :
				//thumbnail_medium
				$data = simplexml_load_file ( "http://vimeo.com/api/v2/video/" . $code . ".xml" );
				$thumbnail = $data->video->thumbnail_medium;
				return $thumbnail;
		}
	}
	
	// retrieves infromation and returns title + desc
	public function handleInformation($type, $code) {
		switch ($type) {
			//youtube
			case "1" :
				$yt = new Zend_Gdata_YouTube ();
				$youtube_video = $yt->getVideoEntry ( $code );
				$information = array ();
				$information ['title'] = $youtube_video->getTitle ();
				$information ['description'] = $youtube_video->getVideoDescription ();
				$information ['duration'] = $youtube_video->getVideoDuration ();
				//http://img.youtube.com/vi/Y75eFjjgAEc/default.jpg
				return $information;
			//vimeo
			case "2" :
				//thumbnail_medium
				$data = simplexml_load_file ( "http://vimeo.com/api/v2/video/" . $code . ".xml" );
				$thumbnail = $data->video->thumbnail_medium;
				$information = array ();
				$information ['title'] = $data->video->title;
				$information ['description'] = $data->video->description;
				$information ['duration'] = $data->video->duration;
				//http://img.youtube.com/vi/Y75eFjjgAEc/default.jpg
				return $information;
		}
	}

}